import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { checkLiveStatus } from './bilibili/bilibiliApi.js';
import { loadTimeConfig, addTaskToGroup, stopTaskFromGroup } from '../modules/timeconfig.js';
import { handleTimeConfig } from '../modules/timeHandler.js';
import { createLogger } from '../modules/Logger.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const DATA_DIR = path.resolve(__dirname, '../data/bilibili');
const SUBSCRIPTION_DIR = path.join(DATA_DIR, 'subscriptions');

if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR);
if (!fs.existsSync(SUBSCRIPTION_DIR)) fs.mkdirSync(SUBSCRIPTION_DIR);

export class LiveNotificationPlugin extends plugin {
  constructor() {
    super({
      name: '直播通知插件',
      dsc: '订阅B站主播直播通知',
      event: 'message',
      priority: 500,
      rule: [
        { reg: "^#皮皮订阅(\\d+)$", fnc: 'subscribe', permission: 'all' },
        { reg: "^#皮皮取消订阅(\\d+)$", fnc: 'unsubscribe', permission: 'all' },
        { reg: "^#皮皮查看订阅$", fnc: 'viewSubscriptions', permission: 'all' },
        { reg: "^#查看已开播$", fnc: 'viewLiveSubscriptions', permission: 'all' }
      ]
    });
    // 创建日志实例
    this.logger = createLogger(this.name);

    try {
      const config = loadTimeConfig();
      this.intervalConfig = config.PippibiliPlugin;
   //   this.logger.info(`✅ 配置加载成功：${this.intervalConfig}`);
      this.autoStartTask();
    } catch (error) {
    //  this.logger.error(`❌ 配置加载失败：${error.message}`);
    }
  }

  async autoStartTask() {
    if (!this.intervalConfig || this.intervalConfig === 0) {
    //  this.logger.error("⏸️ 时间间隔未配置，插件不会自动启动");
      return;
    }

    try {
      stopTaskFromGroup("直播推送检测");
      const { cronExpression, intervalType, timeValue } = handleTimeConfig(this.intervalConfig, this.name);
    //  this.logger.info(`⏰ 定时任务已启动：每 ${timeValue} ${intervalType}（${cronExpression}）`);
      addTaskToGroup("直播推送检测", this.startLiveCheck.bind(this), cronExpression);
    } catch (error) {
      this.logger.error(`❌ 任务启动失败：${error.message}`);
    }
  }

  async startLiveCheck() {
    this.logger.info('🔍 开始执行直播状态检测...');
    try {
      const groupDirs = fs.readdirSync(SUBSCRIPTION_DIR);
      for (const groupDir of groupDirs) {
        const groupId = path.basename(groupDir);
        const subscriptions = this.loadSubscriptions(path.join(SUBSCRIPTION_DIR, groupDir, 'subscriptions.json'));
        await Promise.all(subscriptions.map(({ userId }) => this.checkAndNotify(groupId, userId)));
      }
    } catch (error) {
      this.logger.error(`❌ 检测执行失败：${error.message}`);
    }
  }

  async checkAndNotify(groupId, userId) {
    try {
      const liveStatus = await checkLiveStatus(userId);
      const statusFile = path.join(SUBSCRIPTION_DIR, groupId, 'notification_status.json');
      let status = this.loadNotificationStatus(statusFile);

      if (liveStatus.is_live) {
        if (status[userId]?.live_id !== liveStatus.live_id) {
          // 记录开播时的关注人数
          status[userId] = {
            live_id: liveStatus.live_id,
            is_live: true,
            last_notified: Date.now(),
            hasSentEndNotification: false,
            start_attention: liveStatus.attention // 新增关注人数记录
          };
          this.saveNotificationStatus(statusFile, status);
          await this.notifyGroup(groupId, liveStatus);
        }
      } else {
        if (status[userId]?.is_live && !status[userId].hasSentEndNotification) {
          // 计算关注人数变化
          const startAttention = status[userId].start_attention || 0;
          const endAttention = liveStatus.attention || 0;
          const attentionChange = endAttention - startAttention;
          liveStatus.attentionChange = attentionChange; // 附加变化值到状态对象

          await this.notifyGroup(groupId, liveStatus, true);
          status[userId].hasSentEndNotification = true;
        }
        status[userId] = { is_live: false };
        this.saveNotificationStatus(statusFile, status);
      }
    } catch (error) {
      this.logger.error(`🔔 通知处理失败：${error.message}`);
    }
  }

  // ------------------------- 完整保留原有功能 -------------------------
  
  async subscribe(e) {
    if (!this.checkAdminPermission(e)) return;

    const userId = e.msg.match(/\d+/)[0];
    const groupId = e.group_id.toString();
    const groupDir = path.join(SUBSCRIPTION_DIR, groupId);

    if (!fs.existsSync(groupDir)) {
      fs.mkdirSync(groupDir);
    }

    const groupFile = path.join(groupDir, 'subscriptions.json');
    let subscriptions = this.loadSubscriptions(groupFile);
    if (!subscriptions.some(sub => sub.userId === userId)) {
      const liveStatus = await checkLiveStatus(userId);
      if (!liveStatus.uname) {
        await e.reply(`无法获取直播间 ${userId} 的信息，订阅失败。`);
        return;
      }

      subscriptions.push({ userId });
      this.saveSubscriptions(groupFile, subscriptions);
      await e.reply(`已订阅用户 ${liveStatus.uname}（ID: ${userId}）的直播通知。`);
      this.logger.info(`群聊 ${groupId} 订阅了直播间 ${userId}`);
    } else {
      await e.reply(`直播间 ${userId} 已经在订阅列表中。`);
    }
  }

  async unsubscribe(e) {
    if (!this.checkAdminPermission(e)) return;

    const userId = e.msg.match(/\d+/)[0];
    const groupId = e.group_id.toString();
    const groupDir = path.join(SUBSCRIPTION_DIR, groupId);
    const groupFile = path.join(groupDir, 'subscriptions.json');

    let subscriptions = this.loadSubscriptions(groupFile);
    const index = subscriptions.findIndex(sub => sub.userId === userId);
    if (index > -1) {
      subscriptions.splice(index, 1);
      this.saveSubscriptions(groupFile, subscriptions);
      await e.reply(`已取消订阅直播间 ${userId} 的直播通知。`);
      this.logger.info(`群聊 ${groupId} 取消订阅了直播间 ${userId}`);
    } else {
      await e.reply(`直播间 ${userId} 不在订阅列表中。`);
    }
  }

  async viewSubscriptions(e) {
    if (!this.checkAdminPermission(e)) return;

    const groupId = e.group_id.toString();
    const groupDir = path.join(SUBSCRIPTION_DIR, groupId);
    const groupFile = path.join(groupDir, 'subscriptions.json');

    let subscriptions = this.loadSubscriptions(groupFile);
    if (subscriptions.length > 0) {
      const subscriptionList = subscriptions.map(sub => `直播间ID: ${sub.userId}`).join('\n');
      await e.reply(`当前订阅的直播间:\n${subscriptionList}`);
    } else {
      await e.reply('订阅列表为空。');
    }
  }

  async viewLiveSubscriptions(e) {
    if (!this.checkAdminPermission(e)) return;

    const groupId = e.group_id.toString();
    const groupDir = path.join(SUBSCRIPTION_DIR, groupId);
    const groupFile = path.join(groupDir, 'subscriptions.json');
    let subscriptions = this.loadSubscriptions(groupFile);
    let liveSubscriptions = [];

    for (const { userId } of subscriptions) {
      const liveStatus = await checkLiveStatus(userId);
      if (liveStatus.is_live) {
        liveSubscriptions.push(liveStatus);
      }
    }

    if (liveSubscriptions.length > 0) {
      const liveList = liveSubscriptions.map(live => `用户: ${live.uname} \n正在直播: ${live.room_title}\n直播链接: ${live.room_url}\n区域: ${live.area_name}`).join('\n\n');
      await e.reply(`当前已开播的直播间:\n${liveList}`);
    } else {
      await e.reply('当前没有已开播的直播间。');
    }
  }

  checkAdminPermission(e) {
    // 主人权限优先判断
    if (e.isMaster) {
      this.logger.info(`👑 主人用户 ${e.user_id} 执行命令`);
      return true;
    }

    // 非主人用户检查群管理权限
    if (!e.member.is_admin) {
      e.reply('❌ 只有群主、管理员或主人可以使用此命令');
      this.logger.error(`🚫 用户 ${e.user_id} 无权限操作`);
      return false;
    }
    return true;
  }

  loadSubscriptions(file) {
    try {
      if (fs.existsSync(file)) {
        const data = fs.readFileSync(file, 'utf-8');
        return JSON.parse(data);
      }
    } catch (error) {
      this.logger.error(`加载订阅列表失败: ${error.message}`);
    }
    return [];
  }

  saveSubscriptions(file, subscriptions) {
    try {
      fs.writeFileSync(file, JSON.stringify(subscriptions, null, 2));
    } catch (error) {
      this.logger.error(`保存订阅列表失败: ${error.message}`);
    }
  }

  loadNotificationStatus(file) {
    try {
      if (fs.existsSync(file)) {
        const data = fs.readFileSync(file, 'utf-8');
        return JSON.parse(data);
      }
    } catch (error) {
      this.logger.error(`加载通知状态失败: ${error.message}`);
    }
    return {};
  }

  saveNotificationStatus(file, status) {
    try {
      fs.writeFileSync(file, JSON.stringify(status, null, 2));
    } catch (error) {
      this.logger.error(`保存通知状态失败: ${error.message}`);
    }
  }

  async notifyGroup(groupId, liveStatus, isEndNotification = false) {
    let message;
    if (isEndNotification) {
      const changeSymbol = liveStatus.attentionChange >= 0 ? '+' : '';
      message = [
        `📴 ${liveStatus.uname} 下播啦`,
        `\n▸ 标题：${liveStatus.room_title}`,
        `\n▸ 分区：${liveStatus.area_name}`,
        `\n▸ 关注人数: ${liveStatus.attention} (${changeSymbol}${liveStatus.attentionChange})`,
        segment.image(liveStatus.room_cover)
      ];
    } else {
      message = [
        `📢 ${liveStatus.uname} 开播啦！`,
        `\n▸ 正在直播: ${liveStatus.room_title}`,
        `\n▸ 标题：${liveStatus.room_title}`,
        `\n▸ 分区: ${liveStatus.area_name}`,
        `\n▸ 开播时间: ${liveStatus.live_time}`,
        `\n▸ 人气: ${liveStatus.online.toLocaleString()}`,
        `\n▸ 关注人数: ${liveStatus.attention}`,
        `\n▸ 直播链接: ${liveStatus.room_url}`,
        segment.image(liveStatus.room_cover)
      ];
    }
    try {
      await Bot.pickGroup(groupId).sendMsg(message);
    } catch (error) {
      this.logger.error(`通知群聊 ${groupId} 失败: ${error.message}`);
    }
  }
}